<?php

namespace common\models;

use common\helpers\commonApi;
use EasyWeChat\Factory;
use Yii;

/**
 * This is the model class for table "{{%vip_log}}".
 *
 * @property int $id
 * @property string|null $orderid 订单号
 * @property int|null $userid 用户id
 * @property string|null $title 标题
 * @property int|null $days 天数
 * @property float|null $amount 金额
 * @property int|null $status 状态
 * @property string|null $create_time 创建时间
 * @property string|null $update_time 修改时间
 * @property string|null $info 卡片信息
 * @property string|null $callback_time 回调时间
 * @property string|null $callback_info 回调信息
 */
class VipLog extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%vip_log}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['userid', 'days', 'status'], 'integer'],
            [['amount'], 'number'],
            [['create_time', 'update_time', 'callback_time'], 'safe'],
            [['info', 'callback_info'], 'string'],
            [['orderid', 'title'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'orderid' => '订单号',
            'userid' => '用户id',
            'title' => '标题',
            'days' => '天数',
            'amount' => '金额',
            'status' => '状态',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
            'info' => '卡片信息',
            'callback_time' => '回调时间',
            'callback_info' => '回调信息',
        ];
    }

    /**
     * 创建订单号
     * @return mixed|string
     */
    public static function makeOrderid()
    {
        $orderId = time() . '' . rand(1000, 9999);
        if (self::find()->where(['orderid' => $orderId])->exists()) {
            $orderId = self::makeOrderid();
        }
        return $orderId;
    }

    /**
     * 购买会员卡
     * @param $id 会员卡id
     * @param $userid 用户id
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function buyCard($id,$userid)
    {
        $card = Vip::find()->where(['id'=>$id,'status'=>1])->one();
        if (!$card){
            return commonApi::message('该会员卡暂未开放',false);
        }
        $system = System::getModel();

        if (!$system->mch_id||!$system->pay_key|| !$system->a_appid) {
            return commonApi::message('请配置微信支付参数！', false);
        }
        $openid = User::find()->where(['id'=>$userid])->select(['openid'])->scalar();
        if (!$openid){
            return commonApi::message('请授权微信！',false);
        }
        $orderid = 'm_'.self::makeOrderid();
        $config = [
            'app_id' => $system->a_appid,
            'mch_id' => $system->mch_id,
            'key' => $system->pay_key,
        ];
        try{
            $app = Factory::payment($config);
            $result = $app->order->unify([
                'body' => '购买会员卡'.$card->days.'天',
                'out_trade_no' => $orderid,
                'total_fee' => $card->amount * 100,
                'notify_url' => Yii::$app->request->hostInfo . '/api/pay-notify/wx-card',
                'trade_type' => 'JSAPI',
                'openid' => $openid,
            ]);
            if ($result['return_code'] == 'SUCCESS' && $result['return_msg'] == 'OK') {
                $model = new self();
                $model->orderid = $orderid;
                $model->userid = $userid;
                $model->amount = $card->amount;
                $model->title = $card->title;
                $model->days = $card->days;
                $model->info = json_encode($card->toArray());
                $model->status = 0;
                if ($model->save()) {
                    $config = $app->jssdk->bridgeConfig($result['prepay_id'], false); // 返回数组
                    return commonApi::message('下单成功', true, $config);
                }
                $msg = commonApi::getModelError($model);
                return commonApi::message($msg, false);
            }
            throw new \Exception('下单失败'.$result['return_msg']);
        }catch (\Exception $e){
            return commonApi::message($e->getMessage(), false);
        }
    }

    /**
     * 回调
     * @param $message 回调信息
     * @param $fail
     * @return bool
     */
    public function callback($message)
    {
        $trans = Yii::$app->db->beginTransaction();
        try{
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order = self::find()->where(['orderid'=>$message['out_trade_no']])->one();
            if (!$order || $order->status!==0) {
                $trans->commit();
                return true;
            }
            $user = User::find()->where(['id'=>$order->userid])->one();
            if (!$user){
                return false;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    if (!$user->end_time){
                        $e_time = time();
                        $s_time = time();
                    }else{
                        if ($user->end_time<time()){
                            $e_time = time();
                            $s_time = time();
                        }else{
                            $e_time = $user->end_time;
                            $s_time = $user->start_time;
                        }
                    }
                    $interval = $order->days * 24 * 3600;
                    $user->start_time = date('Y-m-d H:i:s',$s_time);
                    $user->end_time = date('Y-m-d H:i:s',$e_time+$interval);
                    $order->callback_time = date('Y-m-d H:i:s'); // 更新支付时间为当前时间
                    $order->status = 1;
                    // 用户支付失败
                } elseif ($message['result_code'] === 'FAIL') {
                    $order->status = 2;
                }
            } else {
                $trans->commit();
                return false;
            }
            $order->callback_info = json_encode($message);
            if ($order->save()!==false&&$user->save()!==false){
                $trans->commit();
                return true; // 返回处理完成
            }
            $trans->rollBack();
            return false; // 返回处理完成
        }catch (\Exception $e){
            $trans->rollBack();
            return false;
        }
    }
}
